package com.appspot.aliga;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.aliga.persistence.Gameday;
import com.appspot.aliga.persistence.LeagueTableEntry;
import com.appspot.aliga.persistence.Match;
import com.appspot.aliga.persistence.PersistenceService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@SuppressWarnings("serial")
public class ALigaServlet extends HttpServlet {

	public static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
			"dd.MM.yyyy HH:mm", Locale.GERMAN);
	
	private final static String GET_MATCHES = "getMatches";
	private final static String GET_LEAGUETABLE = "getLeagueTable";
	private final static String GET_GAMEDAYS = "getGamedays";

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain; charset=UTF-8");
		PersistenceService ps = new PersistenceService();
		
		String method = req.getParameter("method");

		int leagueID = 0;
		try {
			leagueID = Integer.parseInt(req.getParameter("leagueID"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		int gameday = 0;
		try {
			gameday = Integer.parseInt(req.getParameter("gameday"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		String json = "";
		
		Gson gson = new GsonBuilder()
	     .setDateFormat("dd.MM.yyyy HH:mm")
	     .create();
		
		//get Matches
		if (GET_MATCHES.equalsIgnoreCase(method) && leagueID > 0 && gameday > 0){
			List<Match> matches = ps.findMatches(leagueID, gameday);
			json = gson.toJson(matches);
			//printMatches(resp, matches);
		}
		
		//get Gamedays
		else if (GET_GAMEDAYS.equalsIgnoreCase(method) && leagueID > 0){
			List<Gameday> gds = ps.findGamedays(leagueID);
			json = gson.toJson(gds);
		}
		
		else if (GET_LEAGUETABLE.equalsIgnoreCase(method) && leagueID > 0){
			List<LeagueTableEntry> entries = ps.findLeagueTableEntries(leagueID);
			json = gson.toJson(entries);
		}
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().println(json);
	}

	private void printMatches(HttpServletResponse resp, List<Match> matches)
			throws IOException {
		for (Match match : matches) {

			String date = dateTimeFormat.format(match.getMatchDate());

			resp.getWriter().println(
					date + ": " + match.getTeam1Name() + " - "
							+ match.getTeam2Name() + ": "
							+ match.getTeam1Result() + " : "
							+ match.getTeam2Result());
		}
		
		resp.getWriter().println();
		resp.getWriter().println();
		resp.getWriter().println("as JSON:");
	}
}
